<template>
  
  <div class="block">
    
    <el-date-picker
      v-model="dateRange"
      type="datetimerange"
      :shortcuts="shortcuts"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :default-value="getLastMonthRange()"
      @change="handleDateChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import dayjs from 'dayjs';
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const value2 = ref('')
const dateRange = ref([]);

const getLastMonthRange = () => {

const startTimet = localStorage.getItem('start_time');
const endTimet = localStorage.getItem('end_time');
let start=null;
let end=null;
// 方法1：判断是否为 null 或空字符串（推荐）
if (startTimet === null || startTimet === '') {
     start = dayjs().subtract(1, 'month').toDate();
localStorage.setItem('start_time',dayjs(start).format('YYYY-MM-DD HH:mm:ss'))
  
} else {
   start=startTimet;
}
if (endTimet === null || endTimet === '') {
   end = dayjs().toDate() ;
   localStorage.setItem('end_time',dayjs(end).format('YYYY-MM-DD HH:mm:ss'))
} else {
   end=endTimet;
}

 
  return [start, end];
};

onMounted(() => {
  // 确保组件加载后立即设置默认值
  dateRange.value = getLastMonthRange();
});
const value1 = ref<[Date, Date]>([
  new Date(2000, 10, 10, 10, 10),
  new Date(2000, 10, 11, 10, 10),
])


const shortcuts = [
  {
    text: '上周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '上月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '前三月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
// 处理日期变化事件
const handleDateChange = (val) => {
  console.log('选择的日期范围：', val);
  debugger;
  localStorage.setItem('start_time',dayjs(val[0]).format('YYYY-MM-DD HH:mm:ss'))
  localStorage.setItem('end_time',dayjs(val[1]).format('YYYY-MM-DD HH:mm:ss'))
  refreshComponent();
};
const refreshComponent = () => {
  // 组件级刷新（保留全局状态）
  router.push({
    path: `/refresh/${Math.random()}`, // 临时路由
    query: { redirect: route.fullPath }
  }).then(() => {
    router.replace(route.query.redirect || '/');
  });
};
</script>
<style scoped>
.block {
  padding: 0px 0;
  text-align: center;
  border-right: solid 0px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 2px;
}
</style>
